package com.cloud.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class ServerWebExchangeUtils {
    public static Map<String, String> getParam(ServerWebExchange exchange) {
        HttpMethod method = exchange.getRequest().getMethod();
        if (Objects.equals(HttpMethod.GET, method)) {
            return handlingGetRequestParam(exchange);
        }
        return handlingPostRequestParam(exchange);
    }

    public static Map<String, String> handlingPostRequestParam(ServerWebExchange exchange) {
        // 这个属性就是readBody 谓词写入的 完整body体内容
        String requestBody = exchange.getAttribute("cachedRequestBodyObject");
        try {
            requestBody = URLDecoder.decode(requestBody, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String contentType = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        //当 参数为 json
        if (Objects.equals(contentType, MediaType.APPLICATION_JSON_VALUE)) {
            JSONObject json = JSONObject.parseObject(requestBody);
            Map<String, Object> innerMap = json.getInnerMap();
            Map<String, String> returnMap = new LinkedHashMap<>();
            innerMap.forEach((k, v) -> returnMap.put(k, String.valueOf(v)));
            return returnMap;
        } else if (Objects.equals(contentType, MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
            String[] params = requestBody.split("&");
            Map<String, String> returnMap = new LinkedHashMap<>();
            String lastKey = "";
            for (int i = 0; i < params.length; i++) {
                int index = params[i].indexOf('=');
                // 处理 value中含 &的情况
                if (index < 0) {
                    returnMap.put(lastKey, returnMap.get(lastKey) + "&" + params[i]);
                    continue;
                }
                // 取第一个=号 后面的都是value
                String value = params[i].substring(index + 1);
                String key = params[i].substring(0, index);
                returnMap.put(key, value);
                lastKey = key;
            }
            return returnMap;
        }
        return new LinkedHashMap<>();
    }

    public static Map<String, String> handlingGetRequestParam(ServerWebExchange exchange)     {
        return exchange.getRequest().getQueryParams().toSingleValueMap();
    }

    public static void main(String[] args) {
        System.out.println(new Date().getTime());
    }
}
